import { _decorator, Component, Node, v3, Vec3, Quat } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Main')
export class Main extends Component {
    
    onLoad () {
        this._initData();
        this._initUI();
        this._initWebsocket();
    }

    _initData() {
        this._websocket = null;
    }

    _initUI() {
        this.ui = cc.director.getScene().getChildByName("UI");
        this.device = cc.director.getScene().getChildByName("Device");

        this.ui.getChildByName("DeviceStateValue").getComponent(cc.LabelComponent).string = "Disconnected";
        this.ui.getChildByName("ControllerStateValue").getComponent(cc.LabelComponent).string = "Disconnected";
    }

    _initWebsocket() {
        this._websocket = new WebSocket("ws://192.168.50.152:5000?role=device");
        this._websocket.onopen = this._onopen.bind(this);
        this._websocket.onmessage = this._onmessage.bind(this);
        this._websocket.onerror = this._onerror.bind(this);
        this._websocket.onclose = this._onclose.bind(this);
    }

    _onopen(event) {
        this.ui.getChildByName("DeviceStateValue").getComponent(cc.LabelComponent).string = "Connected";
    }

    _onmessage(event) {
        let data = JSON.parse(event.data);
        if (data['event'] == 'connected') {
            this.ui.getChildByName("ControllerStateValue").getComponent(cc.LabelComponent).string = "Connected";
        }
        else if (data['event'] == 'disconnected') {
            this.ui.getChildByName("ControllerStateValue").getComponent(cc.LabelComponent).string = "Disconnected";
        }
        else if (data['event'] == 'message') {
            if (data['data']['type'] == 'motion') {
                let quaternionX = parseFloat(data['data']['quaternionX']);
                let quaternionY = parseFloat(data['data']['quaternionY']);
                let quaternionZ = parseFloat(data['data']['quaternionZ']);
                let quaternionW = parseFloat(data['data']['quaternionW']);
                let quat = new Quat();
                quat.x = quaternionX;
                quat.y = quaternionZ;
                quat.z = -quaternionY;
                quat.w = quaternionW;
                this.device.setRotation(quat);
            }
            else if (data['data']['type'] == 'offset') {
                let offsetX = parseFloat(data['data']['offsetX']) / 500;
                let offsetY = parseFloat(data['data']['offsetY']) / 500;
                this.device.setPosition(cc.v3(this.device.position.x + offsetX, this.device.position.y + offsetY, this.device.position.z));
            }
        }
    }

    _onerror(event) {
        console.log("onerror: " + event.data);
        this.ui.getChildByName("DeviceStateValue").getComponent(cc.LabelComponent).string = "Disconnected";
    }

    _onclose(event) {
        this.ui.getChildByName("DeviceStateValue").getComponent(cc.LabelComponent).string = "Disconnected";
    }

    update(dt) {
    }
}
